//
//  PickDateView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/13.
//

import SwiftUI

struct PickDateView: View {
    let title: String
    @Binding var selectedDate: Date
    let yearView : Bool
    let monthView : Bool
    let dayView : Bool
    let hourView : Bool
    let minuteView : Bool
    let secondView : Bool
    
    let onDismiss: () -> Void
    
    init(title: String, selectedDate: Binding<Date> , yearView: Bool, monthView: Bool, dayView: Bool, hourView: Bool, minuteView: Bool, onDismiss: @escaping () -> Void) {
        self.title = title
        self._selectedDate = selectedDate
        self.yearView = yearView
        self.monthView = monthView
        self.dayView = dayView
        self.hourView = hourView
        self.minuteView = minuteView
        self.secondView = false
        self.onDismiss = onDismiss
    }
    
    init(title: String, selectedDate: Binding<Date>, onDismiss: @escaping () -> Void) {
        self.title = title
        self._selectedDate = selectedDate
        self.yearView = true
        self.monthView = true
        self.dayView = true
        self.hourView = true
        self.minuteView = true
        self.secondView = false
        self.onDismiss = onDismiss
    }

    @State private var selectedYear: Int = 2023
    @State private var selectedMonth: Int = 1
    @State private var selectedDay: Int = 1
    @State private var selectedHour: Int = 0
    @State private var selectedMinute: Int = 0
    @State private var selectedSecond: Int = 0
    @State private var days: [Int] = Array(1...31)
    
    private let years = Array(2015...Calendar.current.component(.year, from: Date()))
    private let months = Array(1...12)
    private let hours = Array(0...23)
    private let minutes = Array(0...59)
    private let seconds = Array(0...59)
    
    var body: some View {
        ZStack(alignment: .top) {
            // 自定义弹出层容器
            PopupBottomView(title: title,edgeinsets : EdgeInsets(top: 7, leading: 3, bottom: 20, trailing: 3)) {
                VStack(spacing: 0) {
                    // 年月日选择行
                    HStack(spacing: -10) { // 使用负间距抵消系统默认间距
                        if yearView == true {
                            createPicker("年", selection: $selectedYear, values: years, formatter: "年")
                                .onChange(of: selectedYear) { _ in updateDays() }
                        }
                        if monthView == true {
                            createPicker("月", selection: $selectedMonth, values: months, formatter: "月")
                                .onChange(of: selectedMonth) { _ in updateDays() }
                        }
                        if dayView == true {
                            createPicker("日", selection: $selectedDay, values: days, formatter: "日")
                        }
                        if hourView == true {
                            createPicker("时", selection: $selectedHour, values: hours, formatter: "时")
                        }
                        if minuteView == true {
                            createPicker("分", selection: $selectedMinute, values: minutes, formatter: "分")
                        }
                        if secondView == true {
                            createPicker("秒", selection: $selectedSecond, values: seconds, formatter: "秒")
                        }
                    }
                }
            }
            
            // 确认按钮
            HStack {
                Spacer()
                confirmButton
            }
            .padding(10)
        }
        .onAppear(perform: initializeSelection)
    }
    
    // 创建通用Picker组件
    private func createPicker(_ title: String, selection: Binding<Int>, values: [Int], formatter: String) -> some View {
        Picker(title, selection: selection) {
            ForEach(values, id: \.self) { value in
                Text(String(format: "%d%@", value, formatter)) // 强制用十进制无格式显示
                    .font(.system(size: 14))
                    .padding(.vertical, 2)
                    .padding(.horizontal,2)
                    .tag(value)
            }
        }
        .pickerStyle(.wheel)
        .clipped()
    }
    
    // 确认按钮视图
    private var confirmButton: some View {
        Button(action: confirmSelection) {
            Text("确定")
                .font(.system(size: 14))
                .foregroundColor(.white)
                .padding(.vertical, 5)
                .padding(.horizontal, 7)
                .background(themeManager.themeColor)
                .cornerRadius(5)
        }
    }
    
    // 初始化选择值
    private func initializeSelection() {
        let calendar = Calendar.current
        let components = calendar.dateComponents(
            [.year, .month, .day, .hour, .minute, .second],
            from: selectedDate
        )
        selectedYear = components.year ?? 2023
        selectedMonth = components.month ?? 1
        selectedDay = components.day ?? 1
        selectedHour = components.hour ?? 0
        selectedMinute = components.minute ?? 0
        selectedSecond = components.second ?? 0
        updateDays()
    }
    
    // 更新日期范围
    private func updateDays() {
        let calendar = Calendar.current
        let dateComponents = DateComponents(year: selectedYear, month: selectedMonth)
        guard let date = calendar.date(from: dateComponents),
              let range = calendar.range(of: .day, in: .month, for: date) else {
            days = Array(1...31)
            return
        }
        
        let daysCount = range.count
        days = Array(1...daysCount)
        selectedDay = min(selectedDay, daysCount)
    }
    
    // 确认选择
    private func confirmSelection() {
        let components = DateComponents(
            year: selectedYear,
            month: selectedMonth,
            day: selectedDay,
            hour: selectedHour,
            minute: selectedMinute,
            second: selectedSecond
        )
        if let newDate = Calendar.current.date(from: components) {
            selectedDate = newDate
        }
        onDismiss()
    }
}

// 预览
#Preview {
    PickDateView(
        title: "选择时间",
        selectedDate: .constant(Date()),
        onDismiss: {}
    )
}
